package com.dove.kuaizishareas.wificonnection;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnClickListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dove.kuaizishareas.R;

public class WifiReceive extends Activity {

	private TextView ReceiveRemind = null;// 提醒客户用的text
	private RelativeLayout progresscontainer = null;// 包含进度条的layout
	private ProgressBar Cyclepb = null;// 等待对方连接圆形进度
	private ProgressBar Horipb = null;// 接受信息进度
	private TextView Protext = null;//接受进度文字显示
	private TextView fileNameText = null;//接受文件名
	private CheckTimeoutThread m_CheckTimeoutThread = null;// 用于检测服务端等待超时的线程

	static FileOutputStream Rev_Fs;

	private boadIpThread boadIP = null;
	private String username = null;
	private String MobileName = null;
	private String FileName = null;
	private String OpponentIP = null;

	private static final int Determine = 10;//确认接收
	private static final int CONFIRM = 11;
	public static final byte CONFIRM_FLAG = 0;
	public static final byte CANCEL_FLAG = 1;

	private DatagramSocket datasocket = null;
	private ServerSocket connectss = null;
	private Socket connectsocket = null;
	private ServerSocket communicate = null;
	private Socket communicatesocket = null;
	private ServerSocket getVcardss = null;
	private Socket getVcardsocket = null;
	
	private WifiManager mWifiManager;
	private WifiInfo mWifiInfo;
	private String ip;
	private WifiReceivered wifiReceivered;
	private GetConnectThread connect;
	private int max;
	private boolean confirmSend = false;
	
	private SendCommunicateThread sendend;

	private final Handler mHandler = new Handler() {
		Bundle b = null;

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case WifiHelper.CONRECEIVE:
				showDialog(Determine);// 调用onCreateDialog
				break;
			case WifiHelper.WIFICONNECT:
				showDialog(CONFIRM);// 调用onCreateDialog
				break;
			case WifiHelper.UDP_SEND:
				ReceiveRemind.setGravity(Gravity.CENTER);
				ReceiveRemind.setText(getString(R.string.udp_send));
				break;
			case Constant.SERVICE_ON:
				ReceiveRemind.setGravity(Gravity.CENTER);
				ReceiveRemind.setText(getString(R.string.server_start));
				break;
			case Constant.MESSAGE_CONNECTED:
				// 使用interrupt停止检测超时线程的运行
				m_CheckTimeoutThread.interrupt();
				m_CheckTimeoutThread = null;
				ReceiveRemind.setGravity(Gravity.CENTER);
				ReceiveRemind.setText(getString(R.string.receiving));
				progresscontainer.removeView(Cyclepb);
				break;
			case Constant.INIT_PROG://开始下载
				max = (int) msg.obj;
				Horipb.setMax(max);
				RelativeLayout.LayoutParams barlp = new RelativeLayout.LayoutParams(
						ViewGroup.LayoutParams.FILL_PARENT, // width
						ViewGroup.LayoutParams.WRAP_CONTENT // height

				);
//				progresscontainer.addView(Horipb, barlp);
				
				Protext.setVisibility(View.VISIBLE);
				fileNameText.setVisibility(View.VISIBLE);
				fileNameText.setText(FileName);
				Horipb.setVisibility(View.VISIBLE);
				break;
			case Constant.UPDATE_PROG://下载进行中
				int progress = (int) msg.obj;
				Horipb.setProgress(progress);
				int mpro = progress*100/max;
				Protext.setText(mpro+"%");
				break;
			case Constant.CONNECT_TIMEOUT:
				AlertDialog dlg4 = new AlertDialog.Builder(WifiReceive.this)
						.setTitle("超时操作").setMessage(
								"您已等待较长时间，是否返回重新操作？选择“是”返回，选择“否”继续等待。")
						.setPositiveButton("是",
								new OnClickListener() {

									public void onClick(DialogInterface dialog,
											int which) {
										onBackPressed();
									}
								}).setNeutralButton("否",
								new OnClickListener() {
									public void onClick(DialogInterface dialog,
											int witch) {
										dialog.dismiss();
										// 监听后运行超时检测线程
										m_CheckTimeoutThread = new CheckTimeoutThread(
												mHandler);
										m_CheckTimeoutThread.start();
									}
								}).create();
				dlg4.show();
				break;
			case Constant.MESSAGE_RECEIVED://接收文件完成

				//完成后改变提示信息
				ReceiveRemind.setText(getString(R.string.receive_end));

				//改变首次连接状态
				confirmSend = true;

				//启动信息交互线程
				GetCommunicateThread getname = new GetCommunicateThread(mHandler);
				getname.start();
				
				//完成后跳转
//				Horipb.setVisibility(View.INVISIBLE);
//				Protext.setVisibility(View.INVISIBLE);
//				Intent i = new Intent(WifiReceive.this, Importing.class);
//				i.putExtra("filepath", WifiHelper.WIFIRECEIVEPATH);
//				startActivity(i);
				break;
			}
		}
	};

	/**************提示对话框***************/
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case Determine:
			Log.i("dove", "wifireceive:filename2:"+FileName);
			String tempinfo = "您是否确认接受对方用户所发送的：" + FileName+"等文件";
			return new AlertDialog.Builder(WifiReceive.this).setTitle("温馨提示")
					.setMessage(tempinfo).setIcon(
							android.R.drawable.ic_dialog_info)
					.setCancelable(false)
					.setPositiveButton("确认", new OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							//启动接收线程
							ServerThread server = new ServerThread(mHandler);
							server.start();
							//发送确认接收消息给发送方
							SendCommunicateThread sp = new SendCommunicateThread(
									CONFIRM_FLAG);
							sp.start();
						}
					}).setNegativeButton("取消", new OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							SendCommunicateThread sp = new SendCommunicateThread(
									CANCEL_FLAG);
							sp.start();
						}
					}).create();
		case CONFIRM:
			Log.i("dove", "wifireceive:MobileName:-"+MobileName);
			String tempstring = "您是否确认接受对方用户的链接请求：" + MobileName;
			return new AlertDialog.Builder(WifiReceive.this).setTitle("温馨提示")
					.setMessage(tempstring).setIcon(
							android.R.drawable.ic_dialog_info)
					.setCancelable(false)
					.setPositiveButton("确认", new OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							
							if(boadIP!=null){
								if(boadIP.isAlive()){
									boadIP.stop();
									boadIP = null;//终止boadIP线程，即停止广播
								}
							}
							
							SendResponseThread sp = new SendResponseThread(
									CONFIRM_FLAG);
							sp.start();
							//启动信息交互线程
							GetCommunicateThread getname = new GetCommunicateThread(mHandler);
							getname.start();
						}
					}).setNegativeButton("取消", new OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							SendResponseThread sp = new SendResponseThread(
									CANCEL_FLAG);
							sp.start();
						}
					}).create();
		default:
			return null;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wifireceive);
		
		initView();//初始化布局
		
		String ss = getString(R.string.building_server);
//		progresscontainer.removeView(Horipb);
		ReceiveRemind.setText(ss);
		RelativeLayout.LayoutParams barlp = new RelativeLayout.LayoutParams(
				ViewGroup.LayoutParams.WRAP_CONTENT, // width
				ViewGroup.LayoutParams.WRAP_CONTENT // height

		);
		progresscontainer.removeView(Cyclepb);
		progresscontainer.addView(Cyclepb, barlp);

		Cyclepb.setVisibility(View.VISIBLE);

		Intent intent = getIntent();
		username = intent.getStringExtra("username");

		DatagramSocket ds;
		try {
			Log.i("dove", "wifireceive:创建并启动发送线程");
			ds = new DatagramSocket(WifiHelper.UDP_BOADCASTPORT);
			ds.setBroadcast(true);
			
			//创建并启动发送线程
			boadIP = new boadIpThread(username, ds);
//			boadIP.start();
			mHandler.obtainMessage(WifiHelper.UDP_SEND).sendToTarget();
		} catch (SocketException e1) {
			System.out.println("广播IP的Socket错了");
			e1.printStackTrace();
		} catch (Exception e) {
			System.out.println("广播IP的Socket错了");
			e.printStackTrace();
		}
		
		Log.i("dove", "wifireceive:启动connect请求监听线程");
		// 启动connect请求监听线程
		connect = new GetConnectThread(mHandler);
//		connect.start();
		mWifiManager = (WifiManager) this.getApplicationContext()
				.getSystemService(Context.WIFI_SERVICE);
		new Thread(){
			@Override
			public void run() {
				mWifiInfo = mWifiManager.getConnectionInfo();
				ip = intToIp(mWifiInfo.getIpAddress());
				Log.i("dove", "wifireceive:热点ip-"+ip);
				while(ip.equals("0.0.0.0")){
					mWifiInfo = mWifiManager.getConnectionInfo();
					ip = intToIp(mWifiInfo.getIpAddress());
					Log.i("dove", "wifireceive:热点ip-"+ip);
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}// 每秒检查一次ip
				}
				boadIP.start();
				connect.start();
			}
		}.start();
	}

	private void initView() {
		progresscontainer = (RelativeLayout) findViewById(R.id.progresscontainer);
		Horipb = (ProgressBar) findViewById(R.id.importbar);
		Cyclepb = (ProgressBar) findViewById(R.id.cyclebar);
		ReceiveRemind = (TextView) findViewById(R.id.btservertext);
		Protext = (TextView) findViewById(R.id.wifireceive_progress);
		fileNameText = (TextView) findViewById(R.id.wifireceive_fileName);
		
		Protext.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_VIEW);
				File file = new File(WifiHelper.WIFIRECEIVEPATH);
				intent.setDataAndType(Uri.fromFile(file), "video/*");
				startActivity(intent);
			}
		});
	}

	/**
	 *  广播自己用户名的线程
	 * 
	 * @author yukunjin
	 * 
	 */
	class boadIpThread extends Thread {

		private String username;

		public boadIpThread(String name, DatagramSocket dsocket)
				throws Exception {
			username = name;
			datasocket = dsocket;
		}

		public void run() {
			try {
				while (true) {
					// 构造发送数据报 把自己的名字发送出去
					byte[] data = username.getBytes();
					DatagramPacket outgoing = new DatagramPacket(data,
							data.length, InetAddress
									.getByName("192.168.43.255"),
							WifiHelper.UDP_BOADCASTPORT);
					// 发送数据报
					datasocket.send(outgoing);
					Log.i("dove", "wifireceive:广播IP地址ַ-"+username.toString());
					Thread.sleep(1000);// 每秒广播一次
				}
			} catch (Exception e) {
				Log.i("dove", "wifireceive:广播IP地址的socket出错");
			} finally {
				// �ر�dsocket
				Log.i("dove", "wifireceive:关闭广播IP地址的socket");
				if (datasocket != null)
					datasocket.close();
			}
		}
	}

	/***
	 * 监听发送方connect请求的线程
	 * 
	 * @author yukunjin
	 * 
	 */
	class GetConnectThread extends Thread {
		private InputStream instrm = null;
		private final Handler tHandler;

		GetConnectThread(Handler handler) {
			tHandler = handler;
		}

		public void run() {

			try {
				connectss = new ServerSocket(WifiHelper.TCP_CONNECTPORT);
				Log.i("dove", "wifireceive::ConnectListening...");
				// accept阻塞直到被连接
				connectsocket = connectss.accept();
				Log.i("dove", "wifireceive::Connected...");
				// 阻塞运行
				instrm = connectsocket.getInputStream();
				MobileName = getMobilename(instrm);
				tHandler.obtainMessage(WifiHelper.WIFICONNECT).sendToTarget();
				OpponentIP = connectsocket.getInetAddress().toString();
				OpponentIP = OpponentIP.substring(1);
				System.out.println("发送方的IP地址ַ==" + OpponentIP);
				Log.i("dove", "发送方的IP地址ַ==" + OpponentIP);
				datasocket.close();

			} catch (Exception e) {
				Log.i("dove", "wifireceive:Connect请求线程出错");
				System.out.println("Connect请求线程出错");
				e.printStackTrace();
			}
		}
	}

	private String getMobilename(InputStream instrm) {

		byte[] buffer = new byte[WifiHelper.NAME_BUFFER_LENGTH];
		try {
			instrm.read(buffer);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String newstr = null;
		try {
			newstr = new String(buffer,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("对方用户名==" + newstr);
		return newstr;
	}

	/**
	 * 向发送方发送响应的线程
	 * 
	 * @author yukunjin
	 * 
	 */
	class SendResponseThread extends Thread {

		private OutputStream outStrm = null;
		byte flag = 0;

		public SendResponseThread(byte FLAG) {
			flag = FLAG;
		}

		public void run() {
			try {
				// 阻塞运行
				outStrm = connectsocket.getOutputStream();
				outStrm.write(flag & 0x000000ff);
				System.out.println("发送响应的flag==" + flag);

				if (flag == CANCEL_FLAG) {
					onBackPressed();
				}
				outStrm.close();
				connectsocket.close();
				connectss.close();
			} catch (IOException e) {

				try {
					if (connectss != null)
						connectss.close();
					if (connectsocket != null)
						connectsocket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				try {
					if (outStrm != null)
						outStrm.close();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	private class CheckTimeoutThread extends Thread {
		Handler mhandler = null;

		CheckTimeoutThread(Handler mhandler) {
			this.mhandler = mhandler;
		}

		public void run() {
			try {
				Thread.sleep(WifiHelper.timecheck);
				mhandler.obtainMessage(Constant.CONNECT_TIMEOUT).sendToTarget();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
			}
		}
	}

	/**
	 * 按照协议接收文件的线程
	 * 
	 * @author yukunjin
	 */
	class ServerThread extends Thread {

		private InputStream instrm = null;
		private OutputStream outstream = null;
		private final Handler tHandler;
		byte ack[] = new byte[3];//  这个ack数组是为了强制双方数据传递同步

		ServerThread(Handler handler) {
			tHandler = handler;
			ack[0] = 'a';
			ack[1] = 'c';
			ack[2] = 'k';
		}

		public void run() {
			byte headtype = 0;

			try {
				getVcardss = new ServerSocket(WifiHelper.TCP_TRANSMISSIONPORT);
				System.out.println("接收文件的Listening...");
				Log.i("dove", "wifireceive:接收文件的Listening...");
				tHandler.obtainMessage(Constant.SERVICE_ON).sendToTarget();
				// 监听后运行超时检测线程
				m_CheckTimeoutThread = new CheckTimeoutThread(tHandler);
//				m_CheckTimeoutThread.start();
				//  accept阻塞直到被连接
				getVcardsocket = getVcardss.accept();
				System.out.println("接收Vcard的Client Connected...");
				Log.i("dove", "wifireceive:接收Vcard的Client Connected...");
				tHandler.obtainMessage(Constant.MESSAGE_CONNECTED)
						.sendToTarget();
				//阻塞运行
				instrm = getVcardsocket.getInputStream();
				headtype = (byte) instrm.read();

				outstream = getVcardsocket.getOutputStream();
//				outstream.write(ack);
				File mfile = new File(WifiHelper.WIFIRECEIVEPATH);
				if(!mfile.exists()){
					mfile.mkdirs();
				}
				Rev_Fs = new FileOutputStream(new File(
						WifiHelper.WIFIRECEIVEPATH+FileName));
				ReceiveContent(headtype, instrm, outstream, ack);

				getVcardsocket.close();
				getVcardss.close();
				
				tHandler.obtainMessage(Constant.MESSAGE_RECEIVED)
				.sendToTarget();
				
			} catch (Exception e) {
				Log.i("dove", "wifireceive:接收文件的error...");
				e.printStackTrace();
			} finally {
				try {
					if (getVcardsocket != null)
						getVcardsocket.close();
					if (getVcardss != null)
						getVcardss.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					Log.i("dove", "wifireceive:socket close error...");
					e.printStackTrace();
				}
			}
		}
	}

	/************ 接收文件的内容 *************/
	private void ReceiveContent(byte headtype, InputStream instrm,
								OutputStream outstream, byte ack[]) {

//		if (headtype == BluetoothCS.END)
//			return;
		byte lengthhighhigh, lengthhighlow, lengthlowhigh, lengthlowlow;
		try {
			System.out.println("从这里开始接收文件");
			// lengthhighhigh = (byte) instrm.read();
			// lengthhighlow = (byte) instrm.read();
			// lengthlowhigh = (byte) instrm.read();
			// lengthlowlow = (byte) instrm.read();
			byte[] lengthbyte = new byte[4];
			instrm.read(lengthbyte);
			lengthhighhigh = lengthbyte[3];
			lengthhighlow = lengthbyte[2];
			lengthlowhigh = lengthbyte[1];
			lengthlowlow = lengthbyte[0];

			int ContentLength = fourBytetoInt(lengthhighhigh, lengthhighlow,
					lengthlowhigh, lengthlowlow);

			Message m = new Message();
			m.what = Constant.INIT_PROG;
			m.obj = ContentLength;
			mHandler.sendMessage(m);
			Log.i("dove", "wifireceive:length is-"+ContentLength);
//			outstream.write(ack);

			byte[] buffer = new byte[WifiHelper.WIFI_BUFFER_LENGTH];
			int left = ContentLength;
			int readonce = 0;
			while (left > 0) {
				readonce = instrm.read(buffer);
//				outstream.write(ack);
				left = left - readonce;

				Rev_Fs.write(buffer, 0, readonce);
				System.out.println("left2 length is " + left);

				Message m1 = new Message();
				m1.what = Constant.UPDATE_PROG;
				m1.obj = ContentLength - left;
				mHandler.sendMessage(m1);
			}

			instrm.close();
			outstream.close();

		} catch (IOException e) {
			Log.i("dove", "WifiReceive:接收文件的error------");
			// TODO Auto-generated catch block
			try {
				instrm.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
		}

	}

	/************* 合并文件的高低字节以得到文件的长度 **************/
	public static int fourBytetoInt(byte Highhigh, byte Highlow, byte Lowhigh,
									byte Lowlow) {
		int Int = 0;
		Int = Highhigh;
		Int = (int) (Int << 24);
		Int = Int + (0x00FF0000 & ((int) Highlow << 16));
		Int = Int + (0x0000FF00 & ((int) Lowhigh << 8));
		Int = Int + (0x000000FF & ((int) Lowlow));
		return Int;
	}

	/*************** 点击了“返回”按钮 *****************/
	public void onmain(View view) {
		try {
			if (getVcardsocket != null)
				getVcardsocket.close();
			if (getVcardss != null)
				getVcardss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// onBackPressed();
		Intent i = new Intent(WifiReceive.this, NewMain.class);
		i.setFlags(i.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(i);
	}

	@Override
	protected void onStop() {
		boadIP = null;
		if (datasocket != null) {
			datasocket.close();
		}

		if(sendend != null){
			if(sendend.isAlive()){
				sendend.stop();
			}
		}

		try {
			if (getVcardsocket != null)
				getVcardsocket.close();
			if (getVcardss != null)
				getVcardss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			if (connectsocket != null)
				connectsocket.close();
			if (connectss != null)
				connectss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			if (communicatesocket != null)
				communicatesocket.close();
			if (communicate != null)
				communicate.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		super.onStop();
	}

	@Override
	public void onBackPressed() {
		boadIP = null;
		if (datasocket != null) {
			datasocket.close();
		}

		try {
			if (getVcardsocket != null)
				getVcardsocket.close();
			if (getVcardss != null)
				getVcardss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			if (connectsocket != null)
				connectsocket.close();
			if (connectss != null)
				connectss.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			if (communicatesocket != null)
				communicatesocket.close();
			if (communicate != null)
				communicate.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if(sendend != null){
			if(sendend.isAlive()){
				sendend.stop();
			}
		}

		Intent i = new Intent(WifiReceive.this,
				WifiStart.class);
		startActivity(i);
		super.onBackPressed();
	}

	/*
	 * author:yukunjin
	 * 算出ip
	 */
	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
				+ "." + ((i >> 24) & 0xFF);
	}

	/*
	 * author:yukunjin
	 * 监听热点变化
	 */
	private final class WifiReceivered extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(TextUtils.equals(intent.getAction(), "android.net.conn.CONNECTIVITY_CHANGE")){
				boolean wc = wifiConnect(context);
				if(wc){
					boadIP.start();
					connect.start();
					//监听wifi连接成功关闭广播
					if(wifiReceivered!=null){
						unregisterReceiver(wifiReceivered);
					}
				}
			}
		}
	}

	/**
	 * 是否是wifi连接
	 * @param context
	 * @return
	 */
	public static boolean wifiConnect(Context context){
		boolean flag = false;
		ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		State state = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		if(NetworkInfo.State.CONNECTED.equals(state)){
			flag = true;
		}
		return flag;
	}

	/***
	 * 监听发送方发送信息的线程
	 *
	 * @author yukunjin
	 *
	 */
	class GetCommunicateThread extends Thread {
		private InputStream instrm = null;
		private final Handler tHandler;

		GetCommunicateThread(Handler handler) {
			tHandler = handler;
		}

		public void run() {

			try {
				communicate = new ServerSocket(WifiHelper.TCP_CommunicatePORT);
				Log.i("dove", "wifireceive::ConnectListening...");
				// accept阻塞直到被连接
				communicatesocket = communicate.accept();
				Log.i("dove", "wifireceive::Connected...");
				// 阻塞运行
				instrm = communicatesocket.getInputStream();
				FileName = getMobilename(instrm);
				Log.i("dove", "wifireceive:filename1:"+FileName);

				//判断是否首次发送
				if(confirmSend){
					//启动接收线程
					ServerThread server = new ServerThread(mHandler);
					server.start();
					//发送确认接收消息给发送方
					SendCommunicateThread sp = new SendCommunicateThread(
							CONFIRM_FLAG);
					sp.start();
				}else{
					tHandler.obtainMessage(WifiHelper.CONRECEIVE).sendToTarget();
				}

				OpponentIP = communicatesocket.getInetAddress().toString();
				OpponentIP = OpponentIP.substring(1);
				Log.i("dove", "发送方的IP地址==" + OpponentIP);

			} catch (Exception e) {
				Log.i("dove", "wifireceive:Connect请求线程出错");
				System.out.println("Connect请求线程出错");
				e.printStackTrace();
			}
		}
	}

	/**
	 * 向发送方发送信息的线程
	 *
	 * @author yukunjin
	 */
	class SendCommunicateThread extends Thread {

		private OutputStream outStrm = null;
		private byte flag = 0;

		public SendCommunicateThread(byte FLAG) {
			flag = FLAG;
		}

		public void run() {
			try {
				// 阻塞运行
				outStrm = communicatesocket.getOutputStream();
				outStrm.write(flag & 0x000000ff);
				System.out.println("发送响应的flag==" + flag);

				if (flag == CANCEL_FLAG) {
					onBackPressed();
				}
				outStrm.close();
				communicatesocket.close();
				communicate.close();
			} catch (IOException e) {

				try {
					if (communicate != null)
						communicate.close();
					if (communicatesocket != null)
						communicatesocket.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

				try {
					if (outStrm != null)
						outStrm.close();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

}
